//
//  NDUserDefaults.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/16.
//

import Foundation

// MARK: - 存储键定义
let NDPhoneNumberKey = "NDPhoneNumberKey"
let NDAccountIdentifierKey = "accountIdentifierKey"
let NDRegionCodeKey = "regionCodeKey"
let NDContactNumberKey = "contactNumberKey"
let NDAppNameKey = "NDAppNameKey"

var NDLocationReference: String {
    if WJAppEnvironment.shared.currentCountry == .indonesia {
        return "NDLocationIDN"
    } else {
        return "NDLocationIND"
    }
}

let NDCoordinateLatKey = "coordinateLatKey"
let NDCoordinateLngKey = "coordinateLngKey"

let NDAuthProviderKey = "authProviderKey"
let NDAppEntryKey = "appEntryKey"

let NDAuthBeginStampKey = "authBeginStampKey"
let NDAuthCompleteStampKey = "authCompleteStampKey"

let NDNetworkPermissionKey = "networkPermissionKey"

let NDAddressKey = "NDAddressKey"
let NDMarketKey = "NDMarketKey"
let NDloginStartTimeKey = "NDloginStartTimeKey"
let NDloginEndTimeKey = "NDloginEndTimeKey"

// MARK: - 数据存储管理器
class NDUserDefaults {
    private let dataStore: UserDefaults
    
    // 共享实例
    static let shared = NDUserDefaults()
    
    // 私有构造器
    private init() {
        self.dataStore = UserDefaults.standard
    }
    
    // 分组存储初始化
    init(storageGroup: String) {
        self.dataStore = UserDefaults(suiteName: storageGroup)!
    }
    
    // MARK: - 核心存储操作
    
    /// 保存数据项
    func storeValue<T>(_ value: T, using key: String) {
        dataStore.set(value, forKey: key)
        dataStore.synchronize()
    }
    
    /// 读取数据项（必需返回）
    func fetchValue<T>(for key: String, fallback: T) -> T {
        return dataStore.object(forKey: key) as? T ?? fallback
    }
    
    /// 读取数据项（可选返回）
    func fetchOptionalValue<T>(for key: String) -> T? {
        return dataStore.object(forKey: key) as? T
    }
    
    /// 移除数据项
    func removeEntry(for key: String) {
        dataStore.removeObject(forKey: key)
        dataStore.synchronize()
    }
    
    // MARK: - 类型明确的存取方法
    
    func saveText(_ text: String, for key: String) {
        storeValue(text, using: key)
    }
    
    func retrieveText(for key: String) -> String? {
        return fetchOptionalValue(for: key)
    }
    
    func retrieveText(for key: String, default: String) -> String {
        return fetchValue(for: key, fallback: `default`)
    }
    
    func saveInteger(_ number: Int, for key: String) {
        storeValue(number, using: key)
    }
    
    func retrieveInteger(for key: String) -> Int? {
        return fetchOptionalValue(for: key)
    }
    
    func retrieveInteger(for key: String, default: Int) -> Int {
        return fetchValue(for: key, fallback: `default`)
    }
    
    func saveBoolean(_ flag: Bool, for key: String) {
        storeValue(flag, using: key)
    }
    
    func retrieveBoolean(for key: String) -> Bool? {
        return fetchOptionalValue(for: key)
    }
    
    func retrieveBoolean(for key: String, default: Bool) -> Bool {
        return fetchValue(for: key, fallback: `default`)
    }
    
    func saveDecimal(_ number: Double, for key: String) {
        storeValue(number, using: key)
    }
    
    func retrieveDecimal(for key: String) -> Double? {
        return fetchOptionalValue(for: key)
    }
    
    func retrieveDecimal(for key: String, default: Double) -> Double {
        return fetchValue(for: key, fallback: `default`)
    }
    
    func saveFloat(_ number: Float, for key: String) {
        storeValue(number, using: key)
    }
    
    func retrieveFloat(for key: String) -> Float? {
        return fetchOptionalValue(for: key)
    }
    
    func retrieveFloat(for key: String, default: Float) -> Float {
        return fetchValue(for: key, fallback: `default`)
    }
    
    // MARK: - 复杂对象序列化
    
    func archiveObject<T: Encodable>(_ object: T, for key: String) {
        if let serializedData = try? JSONEncoder().encode(object) {
            dataStore.set(serializedData, forKey: key)
            dataStore.synchronize()
        }
    }
    
    func unarchiveObject<T: Decodable>(for key: String, as type: T.Type) -> T? {
        guard let storedData = dataStore.data(forKey: key) else { return nil }
        return try? JSONDecoder().decode(type, from: storedData)
    }
    
    // MARK: - 工具方法
    
    /// 检查键是否存在
    func containsKey(_ key: String) -> Bool {
        return dataStore.object(forKey: key) != nil
    }
    
    /// 清空所有存储
    func purgeAll() {
        if let appBundle = Bundle.main.bundleIdentifier {
            dataStore.removePersistentDomain(forName: appBundle)
            dataStore.synchronize()
        }
    }
    
    /// 批量移除
    func removeMultiple(keys: [String]) {
        keys.forEach { dataStore.removeObject(forKey: $0) }
        dataStore.synchronize()
    }
    
    // MARK: - 业务相关便捷方法
    
    // 用户账户
    func setAccountIdentifier(_ identifier: String) {
        saveText(identifier, for: NDAccountIdentifierKey)
    }
    
    func getAccountIdentifier() -> String? {
        return retrieveText(for: NDAccountIdentifierKey)
    }
    
    // 地区设置
    func setRegionCode(_ code: String) {
        saveText(code, for: NDRegionCodeKey)
    }
    
    func getRegionCode() -> String? {
        return retrieveText(for: NDRegionCodeKey)
    }
    
    // 联系号码
    func setContactNumber(_ number: String) {
        saveText(number, for: NDContactNumberKey)
    }
    
    func getContactNumber() -> String? {
        return retrieveText(for: NDContactNumberKey)
    }
    
    // 坐标信息
    func setGeoCoordinates(latitude: Double, longitude: Double) {
        saveDecimal(latitude, for: NDCoordinateLatKey)
        saveDecimal(longitude, for: NDCoordinateLngKey)
    }
    
    func getGeoCoordinates() -> (latitude: Double?, longitude: Double?) {
        let lat = retrieveDecimal(for: NDCoordinateLatKey)
        let lng = retrieveDecimal(for: NDCoordinateLngKey)
        return (lat, lng)
    }
    
    // 认证时间记录
    func recordAuthStart(_ timestamp: Date) {
        saveDecimal(timestamp.timeIntervalSince1970, for: NDAuthBeginStampKey)
    }
    
    func getAuthStartTime() -> Date? {
        guard let interval = retrieveDecimal(for: NDAuthBeginStampKey) else { return nil }
        return Date(timeIntervalSince1970: interval)
    }
    
    func recordAuthCompletion(_ timestamp: Date) {
        saveDecimal(timestamp.timeIntervalSince1970, for: NDAuthCompleteStampKey)
    }
    
    func getAuthCompletionTime() -> Date? {
        guard let interval = retrieveDecimal(for: NDAuthCompleteStampKey) else { return nil }
        return Date(timeIntervalSince1970: interval)
    }
    
    // 网络权限
    func setNetworkAccess(_ permitted: Bool) {
        saveBoolean(permitted, for: NDNetworkPermissionKey)
    }
    
    func getNetworkAccess() -> Bool {
        return retrieveBoolean(for: NDNetworkPermissionKey, default: false)
    }
    
    // 清理用户会话数据
    func clearSessionData() {
        let sessionKeys = [
            NDAccountIdentifierKey,
            NDContactNumberKey,
            NDAuthBeginStampKey,
            NDAuthCompleteStampKey
        ]
        removeMultiple(keys: sessionKeys)
    }
    
    // MARK: - 高级功能
    
    /// 迁移数据到新键
    func migrateData(from oldKey: String, to newKey: String) -> Bool {
        guard let oldValue = dataStore.object(forKey: oldKey) else { return false }
        dataStore.set(oldValue, forKey: newKey)
        dataStore.removeObject(forKey: oldKey)
        dataStore.synchronize()
        return true
    }
    
    /// 批量存储
    func storeMultiple(values: [String: Any]) {
        values.forEach { key, value in
            dataStore.set(value, forKey: key)
        }
        dataStore.synchronize()
    }
    
    /// 获取所有存储的键
    func getAllKeys() -> [String] {
        return Array(dataStore.dictionaryRepresentation().keys)
    }
}
